package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.spring.SpringUtil;
import com.jsb.laundry.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.model.entity.BusinessType;
import com.jsb.laundry.model.entity.CapitalAccount;
import com.jsb.laundry.model.vo.PayListVo;
import com.jsb.laundry.pay.JSBPay;
import com.jsb.laundry.service.OrderSplittingServiceImpl;
import com.jsb.laundry.service.ServeService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

@Api(tags = {"骑手支付"})
@RestController
@RequestMapping("/qs/")
public class PayController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private ServeService serveService;
    private static WechatMiniPayProperties wechatMiniPayProperties;

    public PayController(WechatMiniPayProperties wechatProperties) {
        PayController.wechatMiniPayProperties = wechatProperties;
    }
    @Resource
    private OrderSplittingServiceImpl orderSplittingService;
    /**
     * 支付列表
     *
     * @return
     */
    @ApiOperation(value = "支付列表", notes = "支付列表", httpMethod = "POST")
    @PostMapping("payList")
    public WebResponse payList() {
        List<PayListVo> payLists = serveService.payList();
        return WebResponse.successData(payLists);
    }

    /**
     * 骑手支付
     *
     * @param object
     * @return
     */
    @ApiOperation(value = "骑手理约金支付", notes = "骑手理约金支付", httpMethod = "POST")
    @PostMapping("payings")
    public WebResponse payings(@RequestBody JSONObject object) {

        LOGGER.info("请求参数" + object);

        String payId = JSBUtil.generateLongOrderId();
        String userId = object.getString("userId");
        if ("".equals(userId) || null == userId) {
            return WebResponse.successData("200", "userId为空", null);
        }
        String openId = serveService.findByOpenId(userId);
        String id = object.getString("id");
        if (JSBUtil.isEmptyString(id)) {
            return WebResponse.failOfParameter();
        }
        Map res = serveService.findServiceById(id);
        int price = (int) res.get("price");
        JSBPay bean = SpringUtil.getBean(JSBPay.class);
        String prepayId = bean.pay(payId, openId, price, "骑手定金", null);
        JSBPay jsbPay = SpringUtil.getBean(JSBPay.class);
        String token = jsbPay.getToken(prepayId);
        //入库
        serveService.addOpenServiceLogInfo(id, userId, payId);

        return WebResponse.successData(token);
    }

    /**
     * 查询用户金额
     *
     * @param object
     * @return
     */
    @ApiOperation(value = "查询用户金额", notes = "查询用户金额", httpMethod = "POST")
    @PostMapping("userInfoMoney")
    public WebResponse userInfoMoney(@RequestBody JSONObject object) {

        LOGGER.info("请求参数" + object);
        String userId = object.getString("userId");
        CapitalAccount byCapitalAccount = serveService.findByCapitalAccount(userId);
        byCapitalAccount.setFrozenAmount(JSBUtil.turnDoubleStrNew(Double.parseDouble(byCapitalAccount.getFrozenAmount())));
        byCapitalAccount.setDeposit(byCapitalAccount.getDeposit());
        byCapitalAccount.setDepositFreeze(byCapitalAccount.getDepositFreeze());
        byCapitalAccount.setWithdraw(Double.parseDouble(JSBUtil.turnDoubleStrNew(Double.parseDouble(String.valueOf(byCapitalAccount.getWithdraw())))));
        String turnDoubleStrNew = JSBUtil.turnDoubleStrNew(byCapitalAccount.getWithdrawFreeze());
        byCapitalAccount.setWithdrawFreezeStr(turnDoubleStrNew);

        byCapitalAccount.setAccountAmountStr(JSBUtil.turnDoubleStrNew(byCapitalAccount.getAccountAmount()));
        String accumulatedIncome = serveService.accumulatedIncome(userId);
        byCapitalAccount.setAccumulatedIncome(JSBUtil.turnDoubleStrNew(Double.parseDouble(accumulatedIncome)));
        byCapitalAccount.setDepositFreezeStr(JSBUtil.turnDoubleStrNew(byCapitalAccount.getDepositFreeze()));
        return WebResponse.successData(byCapitalAccount);
    }

    /**
     * 解密回调返回内容
     *
     * @return
     * @throws Exception
     */
    private String parseCallback(String data) throws Exception {
        // 解析回调中内容
        LOGGER.info("-------支付结果解析:" + data);
        JSONObject json = JSONObject.parseObject(data);
        String ciphertext = json.getJSONObject("resource").getString("ciphertext");
        final String associated_data = json.getJSONObject("resource").getString("associated_data");
        final String nonce = json.getJSONObject("resource").getString("nonce");
        AesUtil aesUtil = new AesUtil(wechatMiniPayProperties.getApiV3Key().getBytes());
        ciphertext = aesUtil.decryptToString(associated_data.getBytes(), nonce.getBytes(), ciphertext);
        return ciphertext;
    }

    @PostMapping("callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 解析回调中内容
        String reqParams = JSBUtil.read(request.getInputStream());
        //TODO 解密回调返回内容(验签)
        String ciphertext = parseCallback(reqParams);
        //支付成功返回的json
        JSONObject payResult = JSONObject.parseObject(ciphertext);
        //支付信息
//        LOGGER.info("-------ciphertext:" + ciphertext);
//        LOGGER.info("-------支付流水号payID:" + payResult.getString("out_trade_no"));
        //TODO 订单支付成功ID
        String payID = payResult.getString("out_trade_no");
        int total = payResult.getJSONObject("amount").getInteger("total");
        if (payID == null) {
            response.setStatus(200);
            response.getWriter().write("{\"code\": \"SUCCESS\",\"message\": \"OK\"}");
            return;
        }
        //查询

        String userId = serveService.findByUserIdAndPayId(payID);
        int byUserId = serveService.findByUserId(userId);
        if (byUserId == 0) {
            serveService.addUserInfo(userId);
        }
        serveService.updByUserId(userId, total);
        serveService.updateStatus(payID);
        //理约金日志
        //根据订单payID查询用户id
        String payid = serveService.payid(payID);
        //查询本账户的资金信息
        CapitalAccount systemAccountInfo = serveService.capitalAccountInfo(payid, "2");
        orderSplittingService.instertAccountLog(systemAccountInfo.getId(),
                "in","骑手理约金"+payid,payid,total, BusinessType.rider_riyokin,(int)systemAccountInfo.getDeposit(),(int)systemAccountInfo.getDepositFreeze()
                ,(int)systemAccountInfo.getWithdraw(),(int)systemAccountInfo.getWithdrawFreeze(),systemAccountInfo.getScore(),(int)systemAccountInfo.getAccountAmount()
                );
        response.setStatus(200);
        response.getWriter().write("{\"code\": \"SUCCESS\",\"message\": \"OK\"}");
    }
    @PostMapping("splitSettled")
    public void splitSettled(@RequestBody JSONObject object){
        String orderId = object.getString("orderId");
        orderSplittingService.splitSettled(orderId);
    }
}
